package com.huluobo.a2112mvvmdouyindemo.home;


import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;


import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.huluobo.a2112mvvmdouyindemo.R;
import com.huluobo.a2112mvvmdouyindemo.adapter.CommonPagerAdapter;
import com.huluobo.a2112mvvmdouyindemo.databinding.FragmentHomeBinding;
import com.huluobo.mvvm_base.view.BaseFragment;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseFragment<FragmentHomeBinding> {
    //tab标签的数据源
    private ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    //fragment的集合
    private List<Fragment> fragments = new ArrayList<>();
    //vp2的adapter
    private CommonPagerAdapter commonPagerAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initData() {
        tabEntities.clear();
        fragments.clear();

        tabEntities.add(new TabEntity("推荐", 0, 0));
        tabEntities.add(new TabEntity("同城", 0, 0));
        tabEntities.add(new TabEntity("关注", 0, 0));

        dataBinding.homeTabLayout.setTabData(tabEntities);

        for (int i = 0; i < tabEntities.size(); i++) {
            fragments.add(new HomeTabFragment());
        }

        commonPagerAdapter = new CommonPagerAdapter(requireActivity(), fragments);
        dataBinding.homeVp2.setAdapter(commonPagerAdapter);
    }

    @Override
    protected void initView() {
        //vp2和tab的联动
        dataBinding.homeVp2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                dataBinding.homeTabLayout.setCurrentTab(position);
            }
        });
        //设置tab和vp2的联动
        dataBinding.homeTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                dataBinding.homeVp2.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }
}